/**
 * 文档分类树组件
 */

import React, { useState, useEffect, useCallback } from 'react';
import { 
  ChevronRight, 
  ChevronDown, 
  Folder,
  FileText,
  Heart,
  Plus,
  MoreHorizontal
} from 'lucide-react';
import type { DocumentCategory } from '@/types/document';
import { useDocument } from '@/contexts/document';

import { showMessage } from '@/components/common/MessageTip';
import CategoryModal from './CategoryModal';
import CategoryContextMenu from './CategoryContextMenu';
import DeleteCategoryModal from './DeleteCategoryModal';

interface CategoryTreeProps {
  className?: string;
}

interface TreeNodeProps {
  category: DocumentCategory;
  level: number;
  selectedCategoryId: string | null;
  onSelect: (categoryId: string | null) => void;
  onToggleExpand: (categoryId: string) => void;
  expandedIds: Set<string>;
  onContextMenu: (e: React.MouseEvent, category: DocumentCategory) => void;
}

// 树节点组件
function TreeNode({ 
  category, 
  level, 
  selectedCategoryId, 
  onSelect, 
  onToggleExpand, 
  expandedIds,
  onContextMenu
}: TreeNodeProps) {
  const hasChildren = category.children && category.children.length > 0;
  const isExpanded = expandedIds.has(category.id);
  const isSelected = selectedCategoryId === category.id;

  const handleToggleExpand = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    if (hasChildren) {
      onToggleExpand(category.id);
    }
  }, [hasChildren, category.id, onToggleExpand]);

  const handleSelect = useCallback(() => {
    onSelect(category.id);
  }, [category.id, onSelect]);

  return (
    <div>
      {/* 当前节点 */}
      <div
        className={`flex items-center px-2 py-1.5 text-sm cursor-pointer rounded-md transition-colors ${
          isSelected 
            ? 'bg-primary/10 text-primary border-l-2 border-primary' 
            : 'text-foreground hover:bg-accent'
        }`}
        style={{ paddingLeft: `${8 + level * 16}px` }}
        onClick={handleSelect}
        onContextMenu={(e) => onContextMenu(e, category)}
      >
        {/* 展开/折叠图标 */}
        <button
          className="w-4 h-4 flex items-center justify-center mr-1 hover:bg-accent rounded"
          onClick={handleToggleExpand}
        >
          {hasChildren ? (
            isExpanded ? (
              <ChevronDown className="w-3 h-3 text-muted-foreground" />
            ) : (
              <ChevronRight className="w-3 h-3 text-muted-foreground" />
            )
          ) : (
            <div className="w-3 h-3" />
          )}
        </button>

        {/* 分类图标 */}
        <div className="w-4 h-4 mr-2 flex items-center justify-center">
          {category.icon ? (
            <span className="text-sm">{category.icon}</span>
          ) : (
            <Folder className="w-4 h-4 text-muted-foreground" />
          )}
        </div>

        {/* 分类名称 */}
        <span className="flex-1 truncate">{category.name}</span>

        {/* 文档数量 */}
        {category.document_count !== undefined && category.document_count > 0 && (
          <span className="text-xs text-muted-foreground ml-2">
            {category.document_count}
          </span>
        )}

        {/* 操作按钮 */}
        <button
          className="w-4 h-4 flex items-center justify-center ml-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded"
          onClick={(e) => {
            e.stopPropagation();
            // TODO: 显示分类操作菜单
          }}
        >
          <MoreHorizontal className="w-3 h-3 text-muted-foreground" />
        </button>
      </div>

      {/* 子节点 */}
      {hasChildren && isExpanded && (
        <div>
          {category.children!.map(child => (
            <TreeNode
              key={child.id}
              category={child}
              level={level + 1}
              selectedCategoryId={selectedCategoryId}
              onSelect={onSelect}
              onToggleExpand={onToggleExpand}
              expandedIds={expandedIds}
              onContextMenu={onContextMenu}
            />
          ))}
        </div>
      )}
    </div>
  );
}

export default function CategoryTree({ className = '' }: CategoryTreeProps) {
  const { 
    categories, 
    selectedCategoryId, 
    fetchCategories, 
    selectCategory,
    addCategory,
    updateCategory,
    deleteCategory,
    loading,
    pagination,
    updateFilter,
    showAllDocuments,
    showFavorites,
    updateShowAllDocuments,
    updateShowFavorites
  } = useDocument();
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  
  // Modal状态管理
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingCategory, setEditingCategory] = useState<DocumentCategory | null>(null);
  
  // 右键菜单状态
  const [contextMenu, setContextMenu] = useState<{
    isOpen: boolean;
    position: { x: number; y: number };
    category: DocumentCategory | null;
  }>({ isOpen: false, position: { x: 0, y: 0 }, category: null });
  
  // 删除确认Modal状态
  const [deleteModal, setDeleteModal] = useState<{
    isOpen: boolean;
    category: DocumentCategory | null;
  }>({ isOpen: false, category: null });

  // 加载分类树
  const loadCategories = useCallback(async () => {
    try {
      await fetchCategories();
    } catch (error) {
      showMessage('error', '加载分类失败');
      console.error('Failed to load categories:', error);
    }
  }, [fetchCategories]);

  // 创建新分类
  const handleCreateCategory = useCallback(() => {
    setEditingCategory(null);
    setIsModalOpen(true);
  }, []);
  
  // 处理分类提交
  const handleCategorySubmit = useCallback(async (categoryData: any) => {
    try {
      await addCategory(categoryData);
      await loadCategories(); // 重新加载分类树
    } catch (error) {
      throw error; // 让Modal处理错误显示
    }
  }, [addCategory, loadCategories]);
  
  // 关闭Modal
  const handleCloseModal = useCallback(() => {
    setIsModalOpen(false);
    setEditingCategory(null);
  }, []);
  
  // 处理右键菜单
  const handleContextMenu = useCallback((e: React.MouseEvent, category: DocumentCategory) => {
    e.preventDefault();
    e.stopPropagation();
    setContextMenu({
      isOpen: true,
      position: { x: e.clientX, y: e.clientY },
      category
    });
  }, []);
  
  // 关闭右键菜单
  const handleCloseContextMenu = useCallback(() => {
    setContextMenu({ isOpen: false, position: { x: 0, y: 0 }, category: null });
  }, []);
  
  // 处理右键菜单操作
  const handleContextMenuAction = useCallback((action: string, category: DocumentCategory) => {
    switch (action) {
      case 'create-child':
        // TODO: 实现创建子分类
        showMessage('success', '创建子分类功能开发中...');
        break;
      case 'edit':
        setEditingCategory(category);
        setIsModalOpen(true);
        break;
      case 'delete':
        setDeleteModal({ isOpen: true, category });
        break;
    }
  }, []);
  
  // 处理分类编辑提交
  const handleCategoryEditSubmit = useCallback(async (categoryData: any) => {
    if (!editingCategory) return;
    
    try {
      await updateCategory(editingCategory.id, categoryData);
      await loadCategories(); // 重新加载分类树
    } catch (error) {
      throw error; // 让Modal处理错误显示
    }
  }, [editingCategory, updateCategory, loadCategories]);
  
  // 处理分类删除
  const handleDeleteCategory = useCallback(async (targetCategoryId?: string) => {
    if (!deleteModal.category) return;
    
    try {
      await deleteCategory(deleteModal.category.id, targetCategoryId);
      await loadCategories(); // 重新加载分类树
      showMessage('success', '分类删除成功');
    } catch (error) {
      showMessage('error', '分类删除失败');
      throw error;
    }
  }, [deleteModal.category, deleteCategory, loadCategories]);
  
  // 关闭删除Modal
  const handleCloseDeleteModal = useCallback(() => {
    setDeleteModal({ isOpen: false, category: null });
  }, []);

  // 组件挂载时加载分类
  useEffect(() => {
    loadCategories();
  }, [loadCategories]);

  // 分类加载后默认展开第一层
  useEffect(() => {
    if (categories.length > 0) {
      const firstLevelIds = categories.map((cat: DocumentCategory) => cat.id);
      setExpandedIds(new Set(firstLevelIds));
    }
  }, [categories]);

  // 切换展开状态
  const handleToggleExpand = useCallback((categoryId: string) => {
    setExpandedIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(categoryId)) {
        newSet.delete(categoryId);
      } else {
        newSet.add(categoryId);
      }
      return newSet;
    });
  }, []);

  // 选择分类
  const handleSelectCategory = useCallback((categoryId: string | null) => {
    // 只更新selectedCategoryId，不触发API请求
    selectCategory(categoryId);
    
    // 如果是切换到分类视图，关闭其他筛选
    if (categoryId !== null) {
      updateShowAllDocuments(false);
      updateShowFavorites(false);
    }
  }, [selectCategory, updateShowAllDocuments, updateShowFavorites]);

  // 后端已经返回了完整的树形结构，直接使用
  const treeData = categories;

  return (
    <div className={`h-full flex flex-col ${className}`}>
      {/* 快速访问区域 */}
      <div className="p-3 border-b border-border">
        <div className="space-y-1">
          {/* 所有文档 */}
          <div
            className={`flex items-center px-2 py-1.5 text-sm cursor-pointer rounded-md transition-colors group ${
              selectedCategoryId === null && showAllDocuments
                ? 'bg-primary/10 text-primary border-l-2 border-primary'
                : 'text-foreground hover:bg-accent'
            }`}
            onClick={() => {
              handleSelectCategory(null);
              updateShowAllDocuments(true);
              // 清除所有筛选条件，显示所有文档
              updateFilter({ isFavorite: undefined, isPinned: undefined });
            }}
          >
            <FileText className="w-4 h-4 mr-2 text-muted-foreground" />
            <span className="flex-1">所有文档</span>
            <span className="text-xs text-muted-foreground">
              {pagination.total}
            </span>
          </div>

          {/* 我的收藏 */}
          <div
            className={`flex items-center px-2 py-1.5 text-sm cursor-pointer rounded-md transition-colors group ${
              showFavorites
                ? 'bg-primary/10 text-primary border-l-2 border-primary'
                : 'text-foreground hover:bg-accent'
            }`}
            onClick={() => {
              // 不清空分类选择，不调用updateFilter，只设置前端显示状态
              updateShowFavorites(true);
            }}
          >
            <Heart className={`w-4 h-4 mr-2 ${showFavorites ? 'text-red-500 fill-current' : 'text-zinc-500'}`} />
            <span className="flex-1">我的收藏</span>
          </div>
        </div>
      </div>

      {/* 分类树区域 */}
      <div className="flex-1 overflow-y-auto">
        <div className="p-3">
          {/* 分类标题和操作 */}
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
              文档分类
            </h4>
            <div className="flex items-center space-x-1">
              <button
                onClick={handleCreateCategory}
                className="w-5 h-5 flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors"
                title="新建分类"
              >
                <Plus className="w-3 h-3" />
              </button>
            </div>
          </div>

          {/* 加载状态 */}
          {loading.categories ? (
            <div className="flex items-center justify-center py-8">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
            </div>
          ) : (
            <>
              {/* 分类树 */}
              {treeData.length > 0 ? (
                <div className="space-y-0.5">
                  {treeData.map(category => (
                    <TreeNode
                      key={category.id}
                      category={category}
                      level={0}
                      selectedCategoryId={selectedCategoryId}
                      onSelect={handleSelectCategory}
                      onToggleExpand={handleToggleExpand}
                      expandedIds={expandedIds}
                      onContextMenu={handleContextMenu}
                    />
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <Folder className="w-12 h-12 text-muted mx-auto mb-3" />
                  <p className="text-sm text-muted-foreground mb-3">暂无分类</p>
                  <p className="text-xs text-muted-foreground/80">
                    系统分类会在后端启动时自动创建
                  </p>
                  <button
                    onClick={handleCreateCategory}
                    className="mt-2 text-xs text-primary hover:text-primary-hover underline"
                  >
                    创建自定义分类
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </div>
      
      {/* 分类管理Modal */}
      <CategoryModal
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        onSubmit={editingCategory ? handleCategoryEditSubmit : handleCategorySubmit}
        categoryToEdit={editingCategory}
        isEditing={!!editingCategory}
        parentCategories={categories}
      />
      
      {/* 右键菜单 */}
      <CategoryContextMenu
        isOpen={contextMenu.isOpen}
        position={contextMenu.position}
        category={contextMenu.category}
        onClose={handleCloseContextMenu}
        onAction={handleContextMenuAction}
      />
      
      {/* 删除确认Modal */}
      <DeleteCategoryModal
        isOpen={deleteModal.isOpen}
        onClose={handleCloseDeleteModal}
        onConfirm={handleDeleteCategory}
        category={deleteModal.category}
        documentCount={0} // TODO: 从API获取实际文档数量
        availableCategories={categories}
      />
    </div>
  );
}
